﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;





namespace WindowsFormsApplication1
{
    public partial class frmBackup : Form
    {
        public frmBackup()
        {
            InitializeComponent();
        }

        private void frmBackup_Load(object sender, EventArgs e)
        {

        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog1.Filter = "SQL Server database backup files|*.bak";
                saveFileDialog1.Title = "Database Backup";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string connStr = "Data Source=.;Initial Catalog=SM;Integrated Security=True;Pooling=False";

                    using (SqlConnection conn = new SqlConnection(connStr))
                    {
                        string sqlStmt = String.Format("BACKUP DATABASE SM TO DISK='{0}'", saveFileDialog1.FileName);

                        using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
                        {
                            conn.Open();
                            bu2.ExecuteNonQuery();
                            conn.Close();

                            MessageBox.Show("Đã backup thành công!");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không được lưu vào ổ hệ thống (C:/)");
            }
 

        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.Filter = "SQL Server database backup files|*.bak";
                openFileDialog1.Title = null;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string connStr = "Data Source=.;Initial Catalog=SM;Integrated Security=True;Pooling=False";

                    using (SqlConnection conn = new SqlConnection(connStr))
                    {
                        string sqlStmt = String.Format("BACKUP DATABASE SM TO DISK='{0}'", openFileDialog1.FileName);

                        using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
                        {
                            conn.Open();
                            bu2.ExecuteNonQuery();
                            conn.Close();

                            MessageBox.Show("Đã restore thành công!");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi chọn file");
            }
        }
    }
}
